package com.ruoyi.scheduler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.domain.MaterielThree;
import com.ruoyi.domain.MaterielTwo;
import com.ruoyi.mapper.MaterielTwoMapper;
import com.ruoyi.utils.CustomSnakeCaseToCamelCaseStrategy;
import com.ruoyi.utils.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.thymeleaf.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class MaterielTwoSchedulerService {
    @Autowired
    MaterielTwoMapper materielTwoMapper;

    @Value("${scheduler.enabled:true}")
    private boolean schedulerEnabled;

    public String getMaterielTwo() {
        String url = "http://192.168.3.35:9990/CROSS/RESTful"; // 第三方API的URL

        // 请求头信息
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("digi-key", "C6BE60050E9039D082A5C045DB8AC4AF");
        headers.put("digi-host", "{\"ver\":\"5.7\",\"prod\":\"YMES\",\"timezone\":\"+8\",\"ip\":\"192.168.3.35\",\"id\":\"\",\"lang\":\"zh_CN\",\"acct\":\"dcms\",\"timestamp\":\"2018071990007275\"}");
        headers.put("digi-service", "{\"prod\":\"E10\",\"ip\":\"192.168.3.35\",\"name\":\"ymes.mo.query\",\"id\":\"DemoCompany_External\"}");
        headers.put("digi-data-exchange-protocol", "1.0");
        headers.put("digi-type", "sync");

        //请求体信息
        String requestBody = "{\t\t\t\n" +
                "\t  \"std_data\": {\t\t\t\n" +
                "\t    \"parameter\": {\t\t\t\n" +
                "\t      \"pageSize\": 5000,\t\t\t\n" +
                "\t      \"pageNo\": 1,\t\t\t\n" +
                "\t      \"isGetSchema\": false,\t\t\t\n" +
                "\t      \"isGetCount\": false,\t\t\t\n" +
                "\t      \"conditions\": [],\t\t\t\n" +
                "\t      \"orders\": []\t\t\t\n" +
                "\t    }\t\t\t\n" +
                "\t  }\t\t\t\n" +
                "\t}\t";
        String response = null;
        try {
            // 调用Get请求
            //String response = HttpUtils.sendGet(url, headers);


            // 调用Post请求
            response = HttpUtils.sendPost(url, headers, requestBody);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }


    public List<MaterielTwo> listMaterielTwo() throws JsonProcessingException {
        //处理接口数据
        String jsonOne = StringUtils.substringAfter(getMaterielTwo(), "[");
        String jsonTwo = StringUtils.substringBefore(jsonOne, "]");
        String jsonStr = "["+jsonTwo+"]";
        ObjectMapper mapper = new ObjectMapper();

        mapper.setPropertyNamingStrategy(new CustomSnakeCaseToCamelCaseStrategy());

        List<MaterielTwo> materielTwos = mapper.readValue(jsonStr, new TypeReference<List<MaterielTwo>>() {});

        for (MaterielTwo materielTwo:materielTwos){
            if(materielTwo.getDocDate() != null) {
                materielTwo.setDocDate(materielTwo.getDocDate().substring(0,10));
            }
            if(materielTwo.getCreateDate() != null) {
                materielTwo.setCreateDate(materielTwo.getCreateDate().substring(0,10));
            }
            if(materielTwo.getLastModifiedDate() != null) {
                materielTwo.setLastModifiedDate(materielTwo.getLastModifiedDate().substring(0,10));
            }
        }
        return materielTwos;
    }



    //@Scheduled(fixedRate = 60000) // 每分钟执行一次
    @Scheduled(fixedRate = 3600000) // 每小时执行一次
    //@Scheduled(fixedRate = 86400000) // 每天执行一次
    @Transactional
    public void scheduleTask() throws JsonProcessingException {
        // 判断是否启用定时任务
        if (!schedulerEnabled || java.lang.management.ManagementFactory.getRuntimeMXBean().getInputArguments().toString().contains("jdwp")) {
            return;
        }
        try {
            List<MaterielTwo> materielTwoList1 = materielTwoMapper.selectAll();//数据库中查所有
            List<MaterielTwo> materielTwoList2= listMaterielTwo();//接口中拿到的数据
            List<MaterielTwo> list =  uniqueListTwo(materielTwoList2, materielTwoList1);///接口中除去数据库中重复的数据
            for(MaterielTwo materielTwo:list){
            /*if(materielTwo.getStatus() != null &&
               (materielTwo.getStatus().equals("2") || materielTwo.getStatus().equals("3"))){
                materielTwoMapper.insertMaterielTwo(materielTwo);//一条条添加到数据库中
            }*/
                materielTwoMapper.insertMaterielTwo(materielTwo);//一条条添加到数据库中
            }
        } catch (JsonProcessingException e) {
            // 记录日志或处理异常
            e.printStackTrace();
        } catch (Exception e) {
            // 处理其他可能的异常
            e.printStackTrace();
        }
    }

    private List<MaterielTwo> uniqueListTwo(List<MaterielTwo> source,List<MaterielTwo> target){
        if(CollectionUtils.isEmpty(source)){
            return List.of();
        }
        if(CollectionUtils.isEmpty(target)){
            return source;
        }
        return source.stream()
                .filter(sc -> target.stream().noneMatch(ta ->
                        sc != null && ta != null  &&
                               /* Objects.equals(sc.getDocDate(), ta.getDocDate()) &&
                                Objects.equals(sc.getDocNo(), ta.getDocNo()) &&
                                Objects.equals(sc.getItemCode(), ta.getItemCode()) &&
                                Objects.equals(sc.getItemDescription(), ta.getItemDescription()) &&
                                Objects.equals(sc.getItemSpecification(), ta.getItemSpecification()) &&
                                Objects.equals(sc.getLotCode(), ta.getLotCode()) &&
                                Objects.equals(sc.getItemDescription1(),ta.getItemDescription1()) &&
                                Objects.equals(sc.getItemCode1(),ta.getItemCode1()) &&
                                Objects.equals(sc.getItemSpecification1(),ta.getItemSpecification1()) &&
                                Objects.equals(sc.getLotCode1(),ta.getLotCode1()) &&
                                Objects.equals(sc.getLotDescription(),ta.getLotDescription()) &&
                                Objects.equals(sc.getRequiredQty(),ta.getRequiredQty()) &&
                                Objects.equals(sc.getRequIncludeMultQty(),ta.getRequIncludeMultQty()) &&
                                Objects.equals(sc.getLeastRequiredQty(),ta.getLeastRequiredQty()) &&
                                Objects.equals(sc.getCreateDate(),ta.getCreateDate()) &&
                                Objects.equals(sc.getUserName1(),ta.getUserName1()) &&
                                Objects.equals(sc.getUserName(),ta.getUserName()) &&
                                Objects.equals(sc.getLastModifiedDate(),ta.getLastModifiedDate()) &&
                                Objects.equals(sc.getApproveStatus(),ta.getApproveStatus()) &&
                                Objects.equals(sc.getUserName2(),ta.getUserName2()) &&
                                Objects.equals(sc.getStatus(),ta.getStatus()) &&
                                Objects.equals(sc.getPlanQty(),ta.getPlanQty()) &&
                                Objects.equals(sc.getItemFeatureCode(),ta.getItemFeatureCode())*/
                                // 只比较关键字段
                                Objects.equals(sc.getDocNo(), ta.getDocNo()) &&
                                Objects.equals(sc.getItemCode(), ta.getItemCode()) &&
                                Objects.equals(sc.getLotCode(), ta.getLotCode()) &&
                                Objects.equals(sc.getDocDate(), ta.getDocDate()) &&
                                Objects.equals(sc.getStatus(),ta.getStatus())
                ))
                .collect(Collectors.toList());
    }

}
